from django.shortcuts import render

import json

from django.http import JsonResponse
from django.core.exceptions import ObjectDoesNotExist

from api.utils import success_response_with_data, failed_response_with_data, list_response
from api.utils_member import get_role
from api.models import BackUser
from api.serializers import BackUserSerializer

from rest_framework import viewsets
from drf_yasg2.utils import swagger_auto_schema
from drf_yasg2 import openapi
from rest_framework.decorators import action


from api.mylogger import logger


class BackUserViewSet(viewsets.ModelViewSet):
    table_name = BackUser._meta.db_table
    serializer_class = BackUserSerializer
    request_body = openapi.Schema(type=openapi.TYPE_OBJECT,
                                  required=['name'],
                                  properties={
                                      "name": openapi.Schema(type=openapi.TYPE_STRING, description="用户名"),
                                      "nickname": openapi.Schema(type=openapi.TYPE_STRING, description="昵称"),
                                      "phone": openapi.Schema(type=openapi.TYPE_STRING, description="手机号"),
                                      "qq_openid": openapi.Schema(type=openapi.TYPE_STRING, description="QQ登录"),
                                      "wechat_openid": openapi.Schema(type=openapi.TYPE_STRING, description="微信登录"),
                                      "passwd": openapi.Schema(type=openapi.TYPE_STRING, description="密码"),
                                      "login_allowed": openapi.Schema(type=openapi.TYPE_BOOLEAN, description="是否允许登录"),
                                      "avatar_url": openapi.Schema(type=openapi.TYPE_STRING, description="头像url"),
                                      "role_id": openapi.Schema(type=openapi.TYPE_INTEGER, description="用户角色Id"),
                                      # 角色的编号，不受名称显示的影响，01,普通会员，02 VIP， 03 超级VIP
                                  }, )

    @swagger_auto_schema(operation_id='添加后台用户', tags=['backuser'], request_body=request_body)
    @action(methods=['POST'], detail=False)
    def backuser_add(self, request):
        data = json.loads(request.body.decode('utf8'))
        serializer = BackUserSerializer(data=data)
        if serializer.is_valid():
            res = serializer.save()
            res_data = {
                "table_name": self.table_name,
                "id": res.id,
            }
            return success_response_with_data(res_data, msg="新增会员成功")
        return JsonResponse(serializer.errors, status=400)

    request_body_mod = openapi.Schema(type=openapi.TYPE_OBJECT,
                                      required=['id', 'name'],
                                      properties={
                                          "id": openapi.Schema(type=openapi.TYPE_INTEGER, description="用户内部id"),
                                          "name": openapi.Schema(type=openapi.TYPE_STRING, description="用户名"),
                                          "nickname": openapi.Schema(type=openapi.TYPE_STRING, description="昵称"),
                                          "phone": openapi.Schema(type=openapi.TYPE_STRING, description="手机号"),
                                          "qq_openid": openapi.Schema(type=openapi.TYPE_STRING, description="QQ登录"),
                                          "wechat_openid": openapi.Schema(type=openapi.TYPE_STRING, description="微信登录"),
                                          "passwd": openapi.Schema(type=openapi.TYPE_STRING, description="密码"),
                                          "login_allowed": openapi.Schema(type=openapi.TYPE_BOOLEAN, description="是否允许登录"),
                                          "avatar_url": openapi.Schema(type=openapi.TYPE_STRING, description="头像url"),
                                          "role_id": openapi.Schema(type=openapi.TYPE_INTEGER, description="用户角色Id"),
                                      }, )

    @swagger_auto_schema(operation_id='修改后台用户', tags=['backuser'], request_body=request_body_mod)
    @action(methods=['POST'], detail=False)
    def backuser_mod(self, request):
        data = json.loads(request.body.decode('utf8'))
        db_id = data.get('id', None)
        if db_id is None:
            return failed_response_with_data(msg="没有id, 修改不了")

        serializer = BackUserSerializer(data=data)
        if serializer.is_valid():
            try:
                db_ret = serializer.update(instance=BackUser.objects.get(id=db_id), validated_data=data)
                res_data = {
                    "table_name": self.table_name,
                    "id": db_ret.id
                }
                return success_response_with_data(res_data, msg="修改会员成功!")
            except ObjectDoesNotExist:
                logger.debug("没有修改记录")
                return failed_response_with_data(msg=self.table_name + f"没有被修改,未发现id为{db_id}的记录")
        return JsonResponse(serializer.errors, status=400)

    @swagger_auto_schema(operation_id='删除会员', tags=['backuser'], request_body=openapi.Schema(
        type=openapi.TYPE_OBJECT,
        properties={
            "id": openapi.Schema(type=openapi.TYPE_INTEGER, description="会员的内部Id"),
        },
    ))
    @action(methods=['POST'], detail=False)
    def backuser_del(self, request):
        data = json.loads(request.body.decode('utf8'))
        db_id = data.get('id', None)
        # qry = Material.objects.filter(id=db_id)
        # print(qry.query)
        deleted_cnt, _ = BackUser.objects.filter(id=db_id).delete()
        res_data = {
            "table_name": self.table_name,
            "id": db_id,
            "rows_deleted": deleted_cnt,
            "info": "删除" + str(deleted_cnt) + "条记录!",
        }
        return success_response_with_data(res_data, msg="删除服务包记录成功!")

    @swagger_auto_schema(operation_id='单个会员信息', tags=['backuser'], request_body=openapi.Schema(
        type=openapi.TYPE_OBJECT,
        properties={
            "id": openapi.Schema(type=openapi.TYPE_INTEGER, description="会员的内部Id"),
        },
    ))
    @action(methods=['POST'], detail=False)
    def backuser_one(self, request):
        data = json.loads(request.body.decode('utf8'))
        db_id = data.get('id', None)
        try:
            qry = BackUser.objects.get(id=db_id)
            serializer = BackUserSerializer(qry)
            return success_response_with_data(serializer.data, msg="查询会员成功!")
        except ObjectDoesNotExist:
            logger.debug("没有发现记录")
            return failed_response_with_data(None, msg=self.table_name + f"未查到id为{db_id}的横幅!")

    @swagger_auto_schema(operation_id='会员列表查询', tags=['backuser'],
                         method='POST',
                         request_body=openapi.Schema(
                             type=openapi.TYPE_OBJECT,
                             properties={
                                 "query": openapi.Schema(type=openapi.TYPE_STRING, description="会员名称的部分信息"),
                             },
                         )
                         )
    @action(methods=['POST'], detail=False)
    def backuser_list(self, request):
        data = json.loads(request.body.decode('utf8'))
        current_page = data.get("pagenum", 1)
        page_size = data.get("pagesize", 10)
        query = data.get("query", '')

        if current_page < 1:
            current_page = 1
        # 为避免大数据量，用这种方式比较合适，不要用Paginator
        start_row = (current_page - 1) * page_size
        end_row = current_page * page_size

        try:
            objects = BackUser.objects
            if len(query):
                objects = objects.filter(name__icontains=query)
            objects = objects.all()
            total = objects.count()
            rows = objects[start_row:end_row]
            logger.debug(f"rows.query {rows.query}")

        except ObjectDoesNotExist:
            logger.debug("没有发现记录")
            return list_response()

        user_list = BackUserSerializer(rows, many=True).data
        for index in range(len(user_list)):
            row = user_list[index]
            role_id = row["role_id"]
            row["role"] = get_role(role_id)
            print(row["role"])


        return list_response(user_list, total, page_size, current_page, self.table_name)
